﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.Xml.Linq;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;

namespace Framework.WebmasterTool.Memberships
{
    public partial class ManagerGroups : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        public string GridViewSortExpression
        {
            get { return ViewState["GridViewSortExpression"] == null ? "RoleName" : ViewState["GridViewSortExpression"] as string; }
            set { ViewState["GridViewSortExpression"] = value; }
        }

        public SortDirection GridViewSortOrder
        {
            get { return ViewState["GridViewSortOrder"] == null ? SortDirection.Ascending : (SortDirection)ViewState["GridViewSortOrder"]; }
            set { ViewState["GridViewSortOrder"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                LoadRoles();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.ManagerUser.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void LoadRoles()
        {
            string strAdministrator = "Super Administrator";
            var roles = new List<aspnet_Roles>();
            MembershipUser currentUser = Membership.GetUser();
            if (currentUser != null && Roles.IsUserInRole(currentUser.UserName, strAdministrator) == true)
            {
                roles = entity.aspnet_Roles.ToList();
            }
            else
            {
                roles = entity.aspnet_Roles.Where(rl => rl.RoleName != strAdministrator).ToList();
            }
            
            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                roles = roles.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                roles = roles.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            grvGroup.DataSource = roles;
            grvGroup.DataBind();
        }

        protected void btnManagerAccount_Click(object sender, EventArgs e)
        {
            Response.Redirect("ManageUsers.aspx");
        }

        protected void grvGroup_Sorting(object sender, GridViewSortEventArgs e)
        {
            //Check if the same column is sorted to switch Sort Order  
            if (GridViewSortExpression.Equals(e.SortExpression))
                GridViewSortOrder = GridViewSortOrder.Equals(SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
            else
                GridViewSortOrder = SortDirection.Ascending;
            //save Sort Expression and Sort Order
            GridViewSortExpression = e.SortExpression;
            if (grvGroup.ToolTip == "all")
                LoadRoles();
            else
                SearchRoles();
        }

        protected void grvGroup_DataBinding(object sender, EventArgs e)
        {
            string srcImageASC = Globals.ApplicationPath + "WebmasterTool/Images/ASC.gif";
            string srcImageDESC = Globals.ApplicationPath + "WebmasterTool/Images/DESC.gif";
            foreach (DataControlField column in grvGroup.Columns)
            {
                //Remove Previous Sort Image  
                column.HeaderText = Regex.Replace(column.HeaderText, "<[^>]*>", "", RegexOptions.IgnoreCase);
                if (column.SortExpression.Equals(GridViewSortExpression))
                {
                    //set new sort image  
                    string strSortImageURL = GridViewSortOrder == SortDirection.Descending ?
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageDESC + "' />" :
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageASC + "' />";
                    column.HeaderText = String.Format("{0}{1}", column.HeaderText, strSortImageURL);
                }
            }
        }

        protected void grvGroup_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvGroup.PageIndex = e.NewPageIndex;
            if (grvGroup.ToolTip == "all")
                LoadRoles();
            else
                SearchRoles();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            grvGroup.PageIndex = 0;
            grvGroup.ToolTip = "search";
            SearchRoles();
        }

        public void SearchRoles()
        {
            var roles = new List<aspnet_Roles>();
            MembershipUser currentUser = Membership.GetUser();
            if (currentUser != null && currentUser.UserName == "admin")
            {
                roles = entity.aspnet_Roles.ToList();
            }
            else
            {
                string strAdministrator = "Super Administrator";
                roles = entity.aspnet_Roles.Where(rl => rl.RoleName != strAdministrator).ToList();
            }

            if (txtSearch.Text.Trim() != "")
            {
                roles = roles.Where(rl => Globals.RemoveSign4VietnameseString(rl.RoleName).ToLower().Contains(Globals.RemoveSign4VietnameseString(txtSearch.Text.Trim()).ToLower())).ToList();
            }
            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                roles = roles.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                roles = roles.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            grvGroup.DataSource = roles;
            grvGroup.DataBind();
        }

        protected void btnCreateGroup_Click(object sender, EventArgs e)
        {
            Response.Redirect("CreateGroup.aspx");
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            XDocument xDocWebconfig = XDocument.Load(HttpContext.Current.Server.MapPath("\\WebmasterTool\\web.config"));
            XElement xEAllowRoles = xDocWebconfig.Descendants("authorization").Descendants("allow").Where(ra => ra.Attribute("roles") != null).FirstOrDefault();
            XElement xEDenyRoles = xDocWebconfig.Descendants("authorization").Descendants("deny").Where(ra => ra.Attribute("roles") != null).FirstOrDefault();
            foreach (GridViewRow row in grvGroup.Rows)
            {
                bool isChecked = ((HtmlInputCheckBox)row.FindControl("chkSelect")).Checked;
                if (isChecked)
                {
                    string roleName = (((HtmlInputCheckBox)row.FindControl("chkSelect")).Attributes["title"].Trim());
                    if (roleName != "Administrator" && roleName != "User" && roleName != "Super Administrator")
                    {
                        string[] users = Roles.GetUsersInRole(roleName);
                        if (users.Count() > 0)
                        {
                            Roles.RemoveUsersFromRole(users, roleName);
                            foreach (var user in users)
                            {
                                Membership.DeleteUser(user);
                            }
                        }
                        Roles.DeleteRole(roleName);

                        //create db log
                        CreateDBLog(null, null, TypeAction.Delete, "Xoá nhóm thành viên: " + roleName, "", "", "", "",
                            "", "", "", "");

                        if (xEDenyRoles.Attribute("roles").Value.Contains(roleName))
                        {
                            xEDenyRoles.Attribute("roles").Value = xEDenyRoles.Attribute("roles").Value.Replace(roleName, "");
                            xEDenyRoles.Attribute("roles").Value = Globals.RemoveMultipeString(xEDenyRoles.Attribute("roles").Value, ",");
                        }
                        if (xEAllowRoles.Attribute("roles").Value.Contains(roleName))
                        {
                            xEAllowRoles.Attribute("roles").Value = xEAllowRoles.Attribute("roles").Value.Replace(roleName, "");
                            xEAllowRoles.Attribute("roles").Value = Globals.RemoveMultipeString(xEAllowRoles.Attribute("roles").Value, ",");
                        }
                    }
                }
            }
            xDocWebconfig.Save(HttpContext.Current.Server.MapPath("\\WebmasterTool\\web.config"));
            if (grvGroup.ToolTip == "all")
                LoadRoles();
            else
                SearchRoles();
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}